package RPC.handler;

import RPC.client.Response;
import RPC.handler.param.ServerRequest;
import RPC.medium.Media;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;


public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("收到客户端得数据"+msg.toString());
        final ServerRequest request = JSONObject.parseObject(msg.toString(), ServerRequest.class);
        Media media= Media.newInstance();
        Response o=  media.process(request);
//        Response o=new Response();
//        o.setId(123L);
//        o.setResult("母鸡喔");
//        o.setCode("00000");
//        o.setMsg("hhhhhhhh");

//        Response response=new Response();
//        response.setId(request.getId());
//        response.setResult("is OK");
//        System.out.println(o.toString());
        ctx.channel().writeAndFlush(JSONObject.toJSONString(o));
        ctx.channel().writeAndFlush("我返回给你的数据");
        ctx.channel().writeAndFlush("\r\n");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleStateEvent event=(IdleStateEvent) evt;
            if (event.equals(IdleStateEvent.READER_IDLE_STATE_EVENT)){
                System.out.println("读空闲");
                ctx.channel().close();
            }else if(event.equals(IdleStateEvent.WRITER_IDLE_STATE_EVENT)){
                System.out.println("写空闲");
            }else if (event.equals(IdleStateEvent.ALL_IDLE_STATE_EVENT)){
                System.out.println("读写空闲");
                ctx.writeAndFlush("ping\r\n");
            }

        }
    }
}
